package vn.gq.udv.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOHelper {

	public static void copy(InputStream is, OutputStream os) throws IOException {
		copy(is, os, null);
	}
	
	public static void copy(InputStream is, OutputStream os, IProgressStatus callback) throws IOException {
		int byteRead = 0;
		byte[] buffer = new byte[4096];
		int totalByteRead = 0;
		while((byteRead = is.read(buffer)) != -1) {
			os.write(buffer, 0, byteRead);
			totalByteRead += byteRead;
			if (callback != null) {
				callback.onPostProgress(totalByteRead);
			}
		}
		is.close();
		os.flush();
		os.close();
	}
	
	public static void writeFile(InputStream is, String path) throws IOException {
		writeFile(is, path, null);
	}
	
	public static void writeFile(InputStream is, String path, IProgressStatus callback) throws IOException {
		mkdirs(path);
		OutputStream os = null;
		os = new BufferedOutputStream(new FileOutputStream(path));
		copy(is, os, callback);
	}
	
	public static void mkdirs(String path) {
		File f = new File(path);
		if (!f.exists()) {
			File p = f.getParentFile();
			if (!p.exists()) {
				p.mkdirs();
			}
		}
	}
	
}
